package practise.alogrithm.introductionToAlogrithm.dataStructures;

import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

/**
 * Created by Richard on 7/20/2014.
 */
public class TwoStackQueue<T> implements Iterable<T> {

    private Stack<T> inputStack;
    private Stack<T> outputStack;

    public TwoStackQueue(){
        inputStack =  new Stack<>();
        outputStack = new Stack<>();
    }

    public void push(T object){

        inputStack.push(object);
    }
    public T pop(){
        return pop(inputStack,outputStack);
    }

    private T pop(Stack<T> input , Stack<T> output){
        if(input.size()==0 && output.size()==0){
            throw new IndexOutOfBoundsException();
        }
        else if(output.size()==0){
            while (input.size()!=0){
                output.push(input.pop());
            }
        }
        return output.pop();

    }

    public static void main(String[] args){
        TwoStackQueue<Integer> queue = new TwoStackQueue<>();
        for(int i =0 ; i <5 ; i++){
            queue.push(i);
        }
        System.out.println("first:"+queue.pop());
        for(int i=6;i<10;i++){
            queue.push(i);
        }
        for(Integer value : queue){
            System.out.print("["+value+"]");
        }
    }

    @Override
    public Iterator<T> iterator() {
        T object = this.pop();
        outputStack.push(object);
        return new QueueIterator(inputStack,outputStack);
    }

    class QueueIterator implements Iterator<T>{

        Stack<T> innerInputStack;
        Stack<T> innerOutputStack;
        public QueueIterator(Stack<T> input, Stack<T> output){
            innerInputStack = (Stack<T>) input.clone();
            innerOutputStack = (Stack<T>) output.clone();
        }

        @Override
        public boolean hasNext() {
            return !innerInputStack.isEmpty()||!innerOutputStack.isEmpty();
        }

        @Override
        public T next() {
            return pop(innerInputStack,innerOutputStack);
        }
    }
}
